#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os,sys
import subprocess
import Time

class Shell(object):
    
    def __init__(self,cmd):
        self.cmd=str(cmd).strip()
        self.time=Time.Time()
        self.pid=None
        self.start_time=None
        self.end_time=None
        self.elapse=0
        self.state=-1
        self.retcode=None
        self.retstr=None
        self.error=None
        self.sp=None
        
    def call(self):
        try:
            start=self.time.timestamp()
            self.start_time=self.time.now()
            self.sp=subprocess.Popen(self.cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            self.retstr,self.error=self.sp.communicate()
            self.end_time=self.time.now()
            self.elapse=self.time.timestamp()-start
            self.pid=self.sp.pid
            self.retcode=self.sp.returncode
            if self.retcode!=0:
                self.state=1
            else:
                self.state=0
        except OSError as error:
            self.error=error
            print >>sys.stderr.write(self.error)
            sys.exit()
        
    def kill(self):
        if self.sp is not None:
            try:
                self.sp.terminate()
            except:
                self.sp.kill()
        
    @property
    def status(self):
        return dict(cmd=self.cmd,pid=self.pid,state=self.state,
                    start_time=self.start_time,end_time=self.end_time,elapse=self.elapse,
                    retcode=self.retcode,retstr=str(self.retstr).strip(),error=str(self.error).strip())
    
    def show(self,sep=': '):
        for key,value in sorted(self.status.items()):
            print '%s%s%s' % (key,sep,value)
    
if __name__ == '__main__':
    shell=Shell('ipconfig /all')
    shell.call()
    shell.show()
